package top.hidoctor.auscultation.feature.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tang.util.AppUtil;
import com.tang.util.DialogUtil;
import com.tang.util.TimeUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.BlueDeviceAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.utils.BlueToothUtils;

import static top.hidoctor.auscultation.utils.BlueToothUtils.getBlueToothUtils;

public class DeviceActivity extends BaseActivity implements View.OnClickListener {
    private static final int MSG_SHOW_CONTENT = 0X1001;
    private static final int MSG_SHOW_BLUE = 0X1002;
    private static final int MSG_SHOW_TOAST = 0X1003;
    public static final String BLUETOOTH_DEVICE = "device";
    private TextView tvNumber, tvStatus;
    private LinearLayout llLabel, llAudit, llDeviceContent, llDownload;
    private RelativeLayout rlAddBluetooth;
    private View viewStatus;
    private Button btnAdd;
    private AlertDialog dialog;
    private HashSet<Object> bluetoothDeviceSet;
    private List<BluetoothDevice> list = new ArrayList<>();
    private BluetoothAdapter bluetoothAdapter;
    //  如果蓝牙没有开启
    private final static int REQUEST_ENABLE = 100;
    private BlueDeviceAdapter deviceAdapter;
    private ImageView ivLoading;
    private Animation operatingAnim;
    private BluetoothDevice device;//当前设备
    private BluetoothGatt bluetoothGatt; //当前配置
    private BlueToothUtils blueToothUtils; //操作库
    private Intent intent;
    private Timer scanTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_device);
        initView();
        initEvent();
    }

    private void initEvent() {
        blueToothUtils = getBlueToothUtils();
        blueToothUtils.setBlueToothHandle(new BlueToothUtils.BlueToothHandle() {
            @Override
            public void getCharacteristicChanged(byte[] data) {

            }

            @Override
            public void stateDisconnected() {
                mHandler.sendEmptyMessage(MSG_SHOW_BLUE);
            }

            @Override
            public void stateDisconnecting() {

            }

            @Override
            public void stateConnected() {
                if (scanTimer != null) {
                    scanTimer.cancel();
                    scanTimer = null;
                }
                bluetoothAdapter.cancelDiscovery();
                mHandler.sendEmptyMessage(MSG_SHOW_CONTENT);
            }

            @Override
            public void stateConnecting() {

            }

            @Override
            public void characteristicWrite(int status) {

            }

            @Override
            public void startWrite() {

            }
        });
    }

    @SuppressLint("NewApi")
    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.tv_title);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFinish();
            }
        });
        tvTitle.setText("设备");


        tvNumber = findViewById(R.id.tv_number);
        tvStatus = findViewById(R.id.tv_status);
        llLabel = findViewById(R.id.ll_label);
        llAudit = findViewById(R.id.ll_audit);
        viewStatus = findViewById(R.id.view_status);
        btnAdd = findViewById(R.id.btn_add);
        rlAddBluetooth = findViewById(R.id.rl_add_bluetooth);
        llDeviceContent = findViewById(R.id.ll_device_content);
        llDownload = findViewById(R.id.ll_download);

        llLabel.setOnClickListener(this);
        llAudit.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        llDownload.setOnClickListener(this);

        if (BlueToothUtils.getDevice() != null && BlueToothUtils.getBluetoothGatt() != null) {
            device = BlueToothUtils.getDevice();
            llDeviceContent.setVisibility(View.VISIBLE);
            rlAddBluetooth.setVisibility(View.GONE);
//            tvNumber.setText(BlueToothUtils.getDevice().getName() + "\n" + BlueToothUtils.getDevice().getAddress());
            tvNumber.setText(BlueToothUtils.getDevice().getAddress());
            tvStatus.setText("在线");
            viewStatus.setBackground(getDrawable(R.drawable.green_point));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_label:
                startActivity(new Intent(this, LabelActivity.class).putExtra(BLUETOOTH_DEVICE, device));
                break;
            case R.id.ll_audit:
                intent = new Intent(this, GatherActivity.class);
                intent.putExtra(BLUETOOTH_DEVICE, device);
                startActivity(intent);
                break;
            case R.id.btn_add:
                list.clear();
                showDialog();
                break;
            case R.id.ll_download:
                intent = new Intent(this, FileDownActivity.class);
                intent.putExtra(BLUETOOTH_DEVICE, device);
                startActivity(intent);
                break;
        }
    }

    /**
     * 显示弹窗
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_bluetooth_list, null);
        builder.setView(dialogView);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        RecyclerView rcBlueTooth = dialogView.findViewById(R.id.rc_bluetooth);
        TextView tvCancel = dialogView.findViewById(R.id.tv_cancel);
        ivLoading = dialogView.findViewById(R.id.iv_loading);
        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
        operatingAnim.setInterpolator(new LinearInterpolator());

        rcBlueTooth.setLayoutManager(new LinearLayoutManager(this));
        rcBlueTooth.setAdapter(deviceAdapter = new BlueDeviceAdapter(R.layout.item_bluetooth_list, list));
        rcBlueTooth.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        deviceAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                device = (BluetoothDevice) deviceAdapter.getData().get(position);
                blueToothUtils.connect(device, DeviceActivity.this);
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothAdapter.cancelDiscovery();
                dialog.dismiss();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (scanTimer != null) {
                    scanTimer.cancel();
                    scanTimer = null;
                }
                list.clear();
                deviceAdapter.notifyDataSetChanged();
            }
        });

        //开始搜索蓝牙设备
        searchBluetooth();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SHOW_CONTENT:
                    dialog.dismiss();
                    llDeviceContent.setVisibility(View.VISIBLE);
                    rlAddBluetooth.setVisibility(View.GONE);
                    tvNumber.setText(device.getAddress());
                    tvStatus.setText("在线");
                    viewStatus.setBackground(getDrawable(R.drawable.green_point));
                    showToast("AI听诊器连接成功");
                    break;
                case MSG_SHOW_BLUE:
                    llDeviceContent.setVisibility(View.GONE);
                    rlAddBluetooth.setVisibility(View.VISIBLE);
                    showToast("AI听诊器断开");
                    break;
                case MSG_SHOW_TOAST:
                    showToast("扫描失败，请重启设备");
                    list.clear();
                    break;
            }
        }
    };


    /**
     * 搜索蓝牙
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void searchBluetooth() {
//        初始化蓝牙扫描 的 set 集合
        bluetoothDeviceSet = new HashSet<>();
//        开始获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                Log.e("TAG", "蓝牙未启动,正在使用 intent 启用蓝牙");
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent, REQUEST_ENABLE);
            } else {
                Log.e("TAG", "蓝牙已经启动，不需要使用 intent 启动蓝牙");
                List<ScanFilter> flilters = new ArrayList<>();
                ScanFilter.Builder builder = new ScanFilter.Builder();
                builder.setServiceUuid(new ParcelUuid(UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")));
                flilters.add(builder.build());
                ScanSettings.Builder builder2 = new ScanSettings.Builder();
                bluetoothAdapter.getBluetoothLeScanner().startScan(flilters, builder2.build(), scanCallback);
                ivLoading.startAnimation(operatingAnim);
                ivLoading.setVisibility(View.VISIBLE);
                Log.e("TAG", "开始扫描蓝牙设备");
                startTime();
            }

        } else {
            showToast("当前设备不支持蓝牙");
        }
    }


    /**
     * 蓝牙搜索四秒后断开
     */
    private void startTime() {
        scanTimer = new Timer();
        scanTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (deviceAdapter.getData().size() == 0) {
                    mHandler.sendEmptyMessage(MSG_SHOW_TOAST);
                    bluetoothAdapter.cancelDiscovery();
                    dialog.dismiss();
                }
            }
        }, 4000);
    }


    //  蓝牙开始扫描回调
    private ScanCallback scanCallback = new ScanCallback() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            //  bluetoothDevice 为扫描到的蓝牙设备
            BluetoothDevice bluetoothDevice = result.getDevice();
            //  添加扫描到的蓝牙设备到 set 集合
            boolean addResult = bluetoothDeviceSet.add(bluetoothDevice);
            //  如果 set 集合中未存在该蓝牙对象，则返回true
            if (addResult) {
                Log.e("TAG", "发现蓝牙设备" + bluetoothDevice.getName() + "," + bluetoothDevice.getAddress());
                list.add(bluetoothDevice);
                deviceAdapter.notifyDataSetChanged();
                ivLoading.clearAnimation();
                ivLoading.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE) {
            if (resultCode == RESULT_OK) {
                Log.e("TAG", "用户允许了开启蓝牙的请求");
                Log.e("TAG", "开始扫描蓝牙设备");
                bluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
                ivLoading.startAnimation(operatingAnim);
                ivLoading.setVisibility(View.VISIBLE);
            } else if (resultCode == RESULT_CANCELED) {
                Log.e("TAG", "用户拒绝了开启蓝牙的请求");
            }
        }
    }

    /**
     * 返回键拦截处理
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onFinish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void onFinish() {
        if (device != null) {
            showAlertDialog("", "确定停止采集吗?", new DialogUtil.DialogButtonClickListener() {
                @Override
                public void onPositiveButtonClick(DialogInterface dialog) {
                    finish();
                    blueToothUtils.off();
                }

                @Override
                public void onNegativeButtonClick(DialogInterface dialog) {
                    dialog.dismiss();
                }
            });
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scanTimer != null) {
            scanTimer.cancel();
            scanTimer = null;
        }
    }
}
